<?php

namespace frontend\modules\resource\logic;

use common\models\Branch;
use common\models\BranchResource;
use common\models\HyAudio;
use common\models\HyBook;
use common\models\HyPeriodical;
use common\models\HyPicture;
use common\models\HyResource;
use common\models\HyVideo;
use frontend\modules\common\models\BaseHelper;
use frontend\modules\common\models\BaseParam;
use Yii;
use yii\data\ActiveDataProvider;
use yii\db\Exception;
use yii\helpers\ArrayHelper;


/**
 * BranchSearch represents the model behind the search form of `common\models\Branch`.
 */
class AdvancedSearchLogic
{


    /**
     * @param string $id
     * @param $type
     * @param $branchId
     * @return int
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    public function addBranchResource($id, $type, $branchId)
    {
        if (empty($id)) {
            $data = $this->_allSearchResult();
        } else {
            $model = (new ResourceLogic())->getResourceModel($type);
            $data = $model->find()
                ->select(['res_id', 'res_title'])
                ->where(['id' => $id])
                ->asArray()
                ->all();
        }
        if (empty($data))
            BaseHelper::Error('没有找到对应资源');

        $sql = "INSERT IGNORE INTO `hy_branch_resource` (`res_id`, `res_title`,`type`,`br_id`) VALUES ";
        $str = '';
        foreach ($data as $key => $val) {
            $str .= '(' . $val['res_id'] . ',\'' . $val['res_title'] . '\',' . $type . ',' . $branchId . ')' . ',';
        };
        $sql .= trim($str, ',');
        $res = Yii::$app->db->createCommand($sql)->execute();
        return $res;
    }

    /**
     * @param $type
     * @return \yii\db\ActiveQuery
     * @throws \yii\base\ExitException
     */
    public function _getQueryModel($type)
    {
        switch ($type) {
            case 1://图书
                $query = HyBook::find()->joinWith(['classes']);
                break;
            case 2://期刊
                $query = HyPeriodical::find()->joinWith(['classes']);
                break;
            case 3://图片
                $query = HyPicture::find()->joinWith(['classes']);
                break;
            case 4://音频
                $query = HyAudio::find()->joinWith(['classes']);
                break;
            case 5://视频
                $query = HyVideo::find()->joinWith(['classes']);
                break;
            default:
                BaseHelper::Error('无效的分类');
                break;
        }

        return $query;
    }

    /**
     * @param $type
     * @param $id
     * @return int
     * @throws \yii\base\ExitException
     */
    public function _getDeleteModel($type, $id)
    {
        switch ($type) {
            case 1://图书
                $res = HyBook::deleteAll(['id' => $id]);
                break;
            case 2://期刊
                $res = HyPeriodical::deleteAll(['id' => $id]);
                break;
            case 3://图片
                $res = HyPicture::deleteAll(['id' => $id]);
                break;
            case 4://音频
                $res = HyAudio::deleteAll(['id' => $id]);
                break;
            case 5://视频
                $res = HyVideo::deleteAll(['id' => $id]);
                break;
            default:
                BaseHelper::Error('无效的分类');
                break;
        }

        return $res;
    }

    /**
     * @param $queryParam
     * @return array
     * @throws \yii\base\ExitException
     */
    public function advancedSearch($queryParam)
    {

        //资源分类
        $type = $queryParam['t'];

        $query = $this->_getQueryModel($type);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => BaseParam::$page,
            ],
        ]);

        // grid filtering conditions
        $query->andFilterWhere([
            'is_self' => 0,
        ]);

        //需要查多个字段
        $filedArr = [
            'res_othertitle' => 'res_title',
            'res_subtitle' => 'res_title',
            'album_title' => 'album_engtitle',
        ];
        foreach ($queryParam['q'] as $key => $val) {
            $query->andFilterWhere(['like', $val['filed_v'], $val['input_v']]);
            if (array_key_exists($val['filed_v'], $filedArr)) {
                $query->andFilterWhere(['like', $filedArr[$val['filed_v']], $val['input_v']]);
            }
        }

        if (!empty($queryParam['sd']) && !empty($queryParam['ed'])) {
            $query->andFilterWhere(['between', 'create_date', $queryParam['sd'], $queryParam['ed']]);
        }
        $q = clone $query;
        //上一次执行存入session
        Yii::$app->session->set('advance_query', $q->createCommand()->getRawSql());
        return [$dataProvider, $type];
    }

    /**
     * @return array
     */
    public function BranchMap()
    {

        $res = (new Branch())->find()
            ->select('id,title')
            ->where(['status' => 1])
            ->asArray()
            ->all();

        $data = ArrayHelper::map(array_merge($res), 'id', 'title');
        return $data;

    }

    /**
     * 批量删除
     * @param $id
     * @param $type
     * @return int
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    public function batchDelete($id, $type)
    {
        if (empty($id)) {
            $res_id = $this->_allSearchResult(true);
        } else {
            $res_id = (new ResourceLogic())->getResourceModel($type);
            $res_id = $res_id->find()->select('res_id')->where(['id' => $id])->indexBy('res_id')->asArray()->all();
            $res_id = array_keys($res_id);
        }

        if (empty($res_id))
            BaseHelper::Error('没有找到对应资源');
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //
            $res = $this->_getDeleteModel($type, $id);
            //主表移除
            HyResource::deleteAll(['id' => $res_id]);

            $res = BranchResource::updateAll(['status' => 0], ['res_id' => $res_id]);
            //在首页 推荐 专题移除  在店铺移除
            (new BranchResourceLogic())->RemoveThird($res_id, $type);

            $transaction->commit();
            return $res;
        } catch (Exception $e) {
            $transaction->rollBack();
            BaseHelper::Error($e->getMessage());
        }

    }

    /**
     * @param $type
     * @return string|\yii\db\DataReader
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    private function _getModelName($type)
    {
        switch ($type) {
            case 1://图书
                $res = "SELECT MAX(create_date) as 'max' ,MIN(create_date) as 'min' FROM `hy_book` WHERE create_date != ''";
                break;
            case 2://期刊
                $res = "SELECT MAX(create_date) as 'max' ,MIN(create_date) as 'min' FROM `hy_periodical` WHERE create_date != ''";
                break;
            case 3://图片
                $res = "SELECT MAX(create_date) as 'max' ,MIN(create_date) as 'min' FROM `hy_picture` WHERE create_date != ''";
                break;
            case 4://音频
                $res = "SELECT MAX(create_date) as 'max' ,MIN(create_date) as 'min' FROM `hy_audio` WHERE create_date != ''";
                break;
            case 5://视频
                $res = "SELECT MAX(create_date) as 'max' ,MIN(create_date) as 'min' FROM `hy_video` WHERE create_date != ''";
                break;
            default:
                BaseHelper::Error('无效的分类');
                break;
        }

        return Yii::$app->db->createCommand($res)->queryOne();
    }

    /**
     * @param $type
     * @return array
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    public function GetYear($type)
    {

        $res = $this->_getModelName($type);
        $max = explode('.', $res['max'])[0];
        $min = explode('.', $res['min'])[0];
        return compact('max', 'min');
    }


    /**
     * @return array
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    private function _allSearchResult($map = false)
    {
        $sql = Yii::$app->session->get('advance_query');


        $sql = str_replace('.*', '.`res_id`,`res_title` ', $sql);
        if (empty($sql))
            BaseHelper::Error('没有检索结果1');
        $res = Yii::$app->db->createCommand($sql)->queryAll();
        if (empty($res))
            BaseHelper::Error('没有检索结果2');
        if ($map) {
            $r = ArrayHelper::map($res, 'res_id', 'res_title');
            return array_keys($r);
        }
        return $res;
    }


}
